package com.sanpu.kxe.business.main.presenter;

import android.app.Activity;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.sanpu.kxe.R;
import com.sanpu.kxe.business.card.view.MyBankListActivity;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.business.main.contract.UserCenterContract;
import com.sanpu.kxe.business.main.model.MainModel;
import com.sanpu.kxe.business.main.provider.MainOpenProvider;
import com.sanpu.kxe.business.member.provider.IMemberProvider;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.common.view.UserCenterItem;
import com.sanpu.kxe.module.luban.Luban;
import com.sanpu.kxe.module.luban.OnRenameListener;
import com.sanpu.kxe.utils.CacheUtil;
import com.sanpu.kxe.utils.DeviceUtil;
import com.sanpu.kxe.utils.IntentTool;
import com.sanpu.kxe.utils.PublicProviderUtil;
import com.sanpu.kxe.utils.ToastUtil;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：个人中心Presenter
 * Created by 薛勇军 on 2018/7/10.
 */

public class UserCenterPresenter implements UserCenterContract.Presenter {

    private UserCenterContract.View mView;

    private CompositeSubscription mSubscription;

    private UserCenterOutput output;

    private ArrayList<View> mPrimaryItemArrayList = new ArrayList<>();

    private File imgFile = null;

    public UserCenterPresenter(UserCenterContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
    }

    /**
     * item点击事件
     */
    private View.OnClickListener mListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.user_name:
                    MainOpenProvider.getInstance().openNickNameModifyActivity(mView.getContext(),
                            output == null ? "" : TextUtils.isEmpty(output.getNickName()) ?
                                    output.getMerchantName() : output.getNickName());
                    break;
                case R.id.user_qrcode:
                    MainOpenProvider.getInstance().openInviteFriendsActivity(mView.getContext());
                    break;
                case R.id.user_wx:
                    MainOpenProvider.getInstance().openMyWxInfoActivity(mView.getContext());
                    break;
                case R.id.user_auth:
                    if (TextUtils.equals(CommonConfig.AUTHEN_AUDIT, output.getChkSts())) {
                        ToastUtil.showTextViewPrompt("正在审核中，请耐心等待");
                        return;
                    }
                    MainOpenProvider.getInstance().openCertificationActivity(mView.getContext());
                    break;
                case R.id.user_banks:
                    IntentTool.startActivity(mView.getContext(), MyBankListActivity.class);
                    break;
                case R.id.user_lvl:
                    IMemberProvider provider = PublicProviderUtil.getProvider(IMemberProvider.class);
                    if (provider != null) {
                        provider.openMemberLevelsListActivity(mView.getContext());
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void showView() {
        try {
            output = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        } catch (ClassCastException e) {
            e.printStackTrace();
        }
        mPrimaryItemArrayList.clear();
//        mPrimaryItemArrayList.add(generateDivView());
        mPrimaryItemArrayList.add(new UserCenterItem(mView.getContext(), R.id.user_name,
                "用户昵称", output == null ? "" : TextUtils.isEmpty(output.getNickName()) ?
                output.getMerchantName() : output.getNickName()));
//        mPrimaryItemArrayList.add(generateDivView());
//        mPrimaryItemArrayList.add(new UserCenterItem(mView.getContext(), R.id.user_qrcode,
//                "我的邀请码", R.drawable.ic_mine_qrcode));
//        mPrimaryItemArrayList.add(new UserCenterItem(mView.getContext(), R.id.user_wx,
//                "我的微信", R.drawable.ic_mine_wx));
//        mPrimaryItemArrayList.add(generateDivView());
        mPrimaryItemArrayList.add(new UserCenterItem(mView.getContext(), R.id.user_auth,
                "实名信息", getAuthText(output.getChkSts())));
//        mPrimaryItemArrayList.add(generateDivView());
//        mPrimaryItemArrayList.add(new UserCenterItem(mView.getContext(), R.id.user_grade,
//                "商户等级", output == null ? "" : output.getLevelName(), 0, false));
//        mPrimaryItemArrayList.add(generateDivView());
        mPrimaryItemArrayList.add(new UserCenterItem(mView.getContext(), R.id.user_phone,
                "手机号码", output == null ? "" : output.getUserName(), 0, false));
//        mPrimaryItemArrayList.add(generateDivView());
        mPrimaryItemArrayList.add(new UserCenterItem(mView.getContext(), R.id.user_banks,
                "银行卡", (output == null ? "0" : output.getCardNum()) + "张"));
//        mPrimaryItemArrayList.add(generateDivView());
//        mPrimaryItemArrayList.add(new UserCenterItem(mView.getContext(), R.id.user_lvl,
//                "会员中心", ""));
        for (int i = 0; i < mPrimaryItemArrayList.size(); i++) {
            final View view = mPrimaryItemArrayList.get(i);
            if (view instanceof UserCenterItem) {
                view.setOnClickListener(mListener);
            }
            mView.addContainerView(view, -1);
        }
    }

    @Override
    public void refreshNickName() {
        try {
            output = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
            ((UserCenterItem) mPrimaryItemArrayList.get(0)).des(output.getNickName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void startUCrop(Uri imageUri) {
        imgFile = new File(CacheUtil.getCacheDirectory(mView.getContext(), null), "userHeadPortrait.png");
        Uri destinationUri = Uri.fromFile(imgFile);
        //初始化，第一个参数：需要裁剪的图片；第二个参数：裁剪后图片
        UCrop uCrop = UCrop.of(imageUri, destinationUri);
        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(mView.getContext(), R.color.c_1d1d1d));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(mView.getContext(), R.color.c_1d1d1d));
        //圆形
        options.setCircleDimmedLayer(true);
        //是否能调整裁剪框
//        options.setFreeStyleCropEnabled(true);
        uCrop.withOptions(options);
        uCrop.withAspectRatio(1, 1); //比例
        uCrop.start((Activity) mView.getContext());
    }

    @Override
    public void startUCrop(Uri imageUri, File file) {
        //裁剪后保存到文件中
        imgFile = file;
        Uri destinationUri = Uri.fromFile(imgFile);
        //初始化，第一个参数：需要裁剪的图片；第二个参数：裁剪后图片
        UCrop uCrop = UCrop.of(destinationUri, destinationUri);
        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(mView.getContext(), R.color.c_1d1d1d));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(mView.getContext(), R.color.c_1d1d1d));
        //圆形
        options.setCircleDimmedLayer(true);
        //是否能调整裁剪框
//        options.setFreeStyleCropEnabled(true);
        uCrop.withOptions(options);
        uCrop.withAspectRatio(1, 1); //比例
        uCrop.start((Activity) mView.getContext());
    }

    @Override
    public void onCompress() {
        if (imgFile == null) return;
        try {
            mView.showLoadingDialog(false, "照片压缩处理中...");
            //同步方法请尽量避免在主线程调用以免阻塞主线程
            Observable.just(imgFile.getPath())
                    .observeOn(Schedulers.io())
                    .map(new Func1<String, List<File>>() {
                        @Override
                        public List<File> call(String filePath) {
                            return luban(filePath, "userHeadPortrait");
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<File>>() {
                        @Override
                        public void onCompleted() {
                            mView.dismissLoadingDialog();
                        }

                        @Override
                        public void onError(Throwable e) {
                            mView.dismissLoadingDialog();
                        }

                        @Override
                        public void onNext(List<File> files) {
                            if (files != null && files.size() > 0) {
                                uploadUserHeadPortrait(files.get(0));
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * luban图片压缩
     *
     * @param filePath 图片地址
     * @param reName   重命名
     * @return
     */
    private List<File> luban(String filePath, final String reName) {
        try {
            // 同步方法直接返回压缩后的文件
            return Luban.with(mView.getContext())
                    .load(filePath)
                    .ignoreBy(CommonConfig.LUBAN_COMPRESSSIZE_PERSONAL)
                    .isNeedDesired(true)
                    .desiredValue(CommonConfig.LUBAN_COMPRESSSIZE_PERSONAL)
                    .setRenameListener(new OnRenameListener() {
                        @Override
                        public String rename(String filePath) {
                            return reName + "_" + System.currentTimeMillis();
                        }
                    })
                    .get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 上传头像
     */
    private void uploadUserHeadPortrait(File imgFile) {
        if (imgFile == null) return;
        final String filePath = imgFile.getPath();
        HashMap<String, File> imgFiles = new HashMap<>();
        imgFiles.put("userHeadPortrait", imgFile);
        mView.showLoadingDialog(true, "正在上传头像...");
        Subscription subscription = MainModel.getInstance().uploadUserHeadPortrait(imgFiles)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(String s) {
                        mView.showHeadImageView(filePath);
                    }
                });
        mSubscription.add(subscription);
    }

    /**
     * 获取认证状态
     *
     * @param chkSts 认证状态
     */
    private String getAuthText(String chkSts) {
        String authStr = "未认证";
        switch (chkSts) {
            case CommonConfig.AUTHEN_NOCOMPLETION:
                authStr = "资料待补全";
                break;
            case CommonConfig.AUTHEN_PASS:
                authStr = "已认证";
                break;
            case CommonConfig.AUTHEN_AUDIT:
                authStr = "审核中";
                break;
            case CommonConfig.AUTHEN_NOPASS:
                authStr = "审核未通过";
                break;
            default:
                break;
        }
        return authStr;
    }

    /**
     * 10dp高的分隔层
     *
     * @return
     */
    private View generateDivView() {
        View view = new View(mView.getContext());
        view.setBackgroundColor(ContextCompat.getColor(mView.getContext(), R.color.c_d9d9d9));
        view.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DeviceUtil.dp2px(1)));
        return view;
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
